<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'category';
    protected $primaryKey = 'cate_id';
    protected $guarded = [];
    public $timestamps = false;

	public function tree()
	{
		$categories = $this->orderBy('cate_order', 'asc')->get();
		return $this->getTree($categories, 'cate_name', 'cate_id', 'cate_pid');
    }


//	public static function tree()
//	{
//		$categories = Category::all();
//		return (new Category)->getTree($categories, 'cate_name', 'cate_id', 'cate_pid');
//    }


	public function getTree($data,$field_name, $field_id = 'id', $field_pid = 'pid', $pid = 0)
	{
		//把数据重新排序
		$result = array();
		foreach ($data as $key => $value) {
			if ($value->$field_pid == $pid) {
				$data[$key]['_' . $field_name] = $data[$key][$field_name];
				$result[] = $data[$key];
				foreach ($data as $k => $v) {
					if ($v->$field_pid == $value->$field_id) {
						$data[$k]['_' . $field_name] = '----' . $data[$k][$field_name];
						$result[] = $data[$k];
					}
				}
			}
		}

		return $result;
	}
}
